﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.AppCode;
using BLL;
using Model;
using Newtonsoft.Json;

namespace WebApplication.Admin
{
    public partial class ProjectForm : BasePage
    {
        AppBLL bll = new AppBLL();
        protected ProjectView model = null;
        protected string ModelJson = "null";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["id"] != null)
            {
                LoadData();
            }
            else
            {
                this.hidID.Value = Guid.Empty.ToString();
            }
        }

        private void LoadData()
        {
            Guid id;
            if (!Guid.TryParse(Request["id"], out id))
            {
                Alert("参数错误！"); return;
            }
            model = bll.GetProjectViewByID(id);
            if (model == null) { Alert("参数错误！"); return; }

            this.hidID.Value = model.Project.ID.ToString();
            WebApplication.AppCode.View.ProjectView view = new AppCode.View.ProjectView();
            view.Project = model.Project;
            view.Nodes = new List<AppCode.View.ProjectNodeView>(model.Nodes.Count);
            model.Nodes.OrderBy(x => x.Order).ToList().ForEach(x =>
            {
                view.Nodes.Add(new AppCode.View.ProjectNodeView
                {
                    AreaID = x.AreaID,
                    BeginDate = x.BeginDate,
                    EndDate = x.EndDate,
                    ID = x.ID,
                    Order = x.Order,
                    ProjectID = x.ProjectID,
                    Status = x.Status,
                    ExpectDays = x.ExpectDays,
                    StandardDays=x.StandardDays,
                    Content = x.Content
                });
            });
            view.Nodes.ForEach(x =>
            {
                var nextNodes = model.Relationships.Where(w => w.NodeID == x.ID).ToList();
                var nextNodeID = from f in nextNodes select f.NextNodeID;
                var nodes = from f in view.Nodes.Where(w => nextNodeID.Contains(w.ID)) select f.Content;
                x.NextNodeName = string.Join(",", nodes.ToArray());
                x.NextNodes = string.Join(",", nextNodeID.ToArray());
            });
            view.Areas = model.Areas.OrderBy(x => x.Order).ToList();
            ModelJson = JsonConvert.SerializeObject(view, Formatting.Indented);
        }
    }
}